package org.replay.controller;
/*
 * Copyright © 2020 lizicong,All rights reserved.
 *
 * Licensed under the GPL License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.replay.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 实在不知道按照规范这东西应该搁哪，就作为控制器吧
 * @author lizicong
 */
@Component
public class ConsumerController {

    @Resource
    OrderService orderService;

    /**
     * 消费订单消息
     *
     * @param msg
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "seckill-queue")
    @RabbitHandler
    public void recMsg(String msg, Channel channel, Message message) {
        System.out.println(">>msg:" + msg);
        try {
            if (orderService.createOrder(msg) == 1) {
                //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                //消息收到了，但处理失败，打日志记录
                System.out.println("receiver fail");
            }
        } catch (IOException e) {
            //丢弃这条消息
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            e.printStackTrace();
        }

    }
}
